﻿/* *** Handle selection by checkboxes *** */
function HandleSelectionByCheckboxes(table, tableInstance, rows_selected, key, cssClass) {
    // Handle click on checkbox
    $('#' + table + ' tbody').on('click', 'input[type="checkbox"]', function (e) {
        var $row = $(this).closest('tr');

        // Get row data
        var data = tableInstance.row($row).data();

        // Get row ID
        //var rowId = data["IDColore"];

        // Determine whether row ID is in the list of selected row IDs 
        //var index = $.inArray(data, rows_selected);
        var index = IsInArray(rows_selected, data, key);

        // If checkbox is checked and row ID is not in list of selected row IDs
        if (this.checked && index === -1) {
            rows_selected.push(data);

            // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
        } else if (!this.checked && index !== -1) {
            rows_selected.splice(index, 1);
        }

        if (this.checked) {
            $row.addClass(cssClass);
        } else {
            $row.removeClass(cssClass);
        }

        // Update state of "Select all" control
        updateDataTableSelectAllCtrl(tableInstance);

        // Prevent click event from propagating to parent
        e.stopPropagation();
    });

    // Handle click on table cells with checkboxes
    $('#' + table).on('click', 'tbody td, thead th:first-child', function (e) {
        $(this).parent().find('input[type="checkbox"]').trigger('click');
    });

    // Handle click on "Select all" control
    $('input[name="select_all"]').on('click', function (e) {
        if (this.checked) {
            $('#' + table + ' tbody input[type="checkbox"]:not(:checked)').trigger('click');
        } else {
            $('#' + table + ' tbody input[type="checkbox"]:checked').trigger('click');
        }

        // Prevent click event from propagating to parent
        e.stopPropagation();
    });

    // Handle table draw event
    tableInstance.on('draw', function () {
        // Update state of "Select all" control
        updateDataTableSelectAllCtrl(tableInstance);
    });
}
/* *** Handle selection by checkboxes *** */

//
// Updates "Select all" control in a data table
//
function updateDataTableSelectAllCtrl(table) {
    var $table = table.table().node();
    var $chkbox_all = $('tbody input[type="checkbox"]', $table);
    var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
    var chkbox_select_all = $('input[name="select_all"]', $table).get(0);

    // If none of the checkboxes are checked
    if ($chkbox_checked.length === 0) {
        chkbox_select_all.checked = false;
        if ('indeterminate' in chkbox_select_all) {
            chkbox_select_all.indeterminate = false;
        }

        // If all of the checkboxes are checked
    } else if ($chkbox_checked.length === $chkbox_all.length) {
        chkbox_select_all.checked = true;
        if ('indeterminate' in chkbox_select_all) {
            chkbox_select_all.indeterminate = false;
        }

        // If some of the checkboxes are checked
    } else {
        chkbox_select_all.checked = true;
        if ('indeterminate' in chkbox_select_all) {
            chkbox_select_all.indeterminate = true;
        }
    }
}

function IsInArray(source, obj, key) {
    for (var i = 0; i < source.length; i++) {
        if (source[i][key] === obj[key]) {
            return i;
        }
    }
    
    return -1;
}

function RedrawGrid(table) { table.draw(); };

/*
  We use Bootstrap theme, so the class selector for the selected row is: ".active" !
*/
function GetSelectedData(table) {
    return table.row('.active').data();
}

function RemoveSelectedData(table) {
    return table.row('.active').remove().draw();
}

function IsRowSelected(table) {
    return (table.row('.active').length > 0);
}

function Empty(table) {
    table.rows().clear().draw();
}

function AddItem(table, item) {
    table.row.add(item).draw();
}

/// <summary>
/// Validates the table parameters.
/// </summary>
/// <param name="controls">Array of control names to be validated</param>
/// <returns>true if the paramenters adre validated, false otherwise</returns>
/// <remarks>
/// One control present in the array of controls is not valid when is value is:
///  - empty
///  - equals to 'undefined' string
///  - null
///  - undefined
/// </remarks>
function ValidateTableParameters(controls) {
    var retValue = true;

    $.each(controls, function (index, item) {

        var value = $("[name='" + item + "']").val();

        if (value == '' || value == 'undefined' || value == null || value == undefined || value == '?') {
            retValue = false;
            return;
        }

    });

    return retValue;
}